<script setup>
import { ref, reactive, onMounted } from 'vue';
import request from '../utils/request.js';
import {
  X,
} from 'lucide-vue-next';


const props = defineProps({
  // 接收父组件传递的用户ID
  avatarModal: {
    type: Boolean,
    required: true, // 必传
  }
})



const emit = defineEmits(['update:avatarModal','update:avatarUrl']); // 声明要触发的事件

const toAvatarModal = () => {
  emit('update:avatarModal', !props.avatarModal);
}
const updateAvatarUrl=()=>{
  emit('update:avatarUrl', avatarUrl.value);
}


// 头像URL
const avatarUrl = ref('');
// 上传进度
const uploadProgress = ref(0);
// 消息提示
const message = reactive({
  show: false,
  text: '',
  type: 'success' // success, error
});
// 允许上传的文件类型
const accept = ref('image/jpeg,image/png,image/jpg,image/gif');
// 当前用户ID（实际从登录态获取）
const email = sessionStorage.getItem('user');

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    if (beforeUpload(file)) {
      handleUpload(file);
    }
    event.target.value = ''; 
  }
};

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    showMessage('请上传图片类型文件', 'error');
    return false;
  }
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    showMessage('图片大小不能超过5MB', 'error');
    return false;
  }
  return true;
};

// 处理文件上传
const handleUpload = async (file) => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('email', email);

  try {
    const response = await request.post('/avatar/upload', formData, {
      onUploadProgress: (e) => {
        uploadProgress.value = Math.round((e.loaded / e.total) * 100);
      }
    });
    const res = await request.post('/avatar/delete', {
      email: email,
      avatarUrl: avatarUrl.value  // 这样会被转换为查询参数：/user/getAvatar?email=xxx
    });
    console.log(res);
    if (response.code == 1) {
      avatarUrl.value = response.data.avatarUrl;
      showMessage('头像上传成功', 'success');
    } else {
      showMessage(response.message, 'error');
    }

    setTimeout(() => {
      uploadProgress.value = 0;
      updateAvatarUrl();
      toAvatarModal();
    }, 1000);
  } catch (error) {
    showMessage('上传失败，请重试', 'error');
    uploadProgress.value = 0;
    console.error('上传失败:', error);
  }
};

// 显示消息提示
const showMessage = (text, type) => {
  message.text = text;
  message.type = type;
  message.show = true;
  setTimeout(() => {
    message.show = false;
  }, 3000);
};

// 初始化获取用户头像
const initAvatar = async () => {
  try {
    const res = await request.get('/user/getAvatar', {
      params: {
        email: email  // 这样会被转换为查询参数：/user/getAvatar?email=xxx
      }
    });
    console.log(res.data.avatarUrl, 555)
    if (res.data.avatarUrl) {
      avatarUrl.value = res.data.avatarUrl;
    }
  } catch (err) {
    console.error('获取头像失败:', err);
  }
};
onMounted(() => {
  initAvatar();
})

</script>

<template>
  <!-- 全屏遮罩层：固定定位+半透明背景，flex 居中内容 -->
  <div class="fixed inset-0 z-50 bg-gray-400/70 flex items-center justify-center p-4">
    <!-- 白色卡片：最大宽度限制为 md（640px），小屏幕自动占满宽度 -->
    <div class="max-w-md w-full p-6 bg-white rounded-lg shadow-md avatar-upload-container">
      <div class="flex">
        <h3 class="text-2xl font-semibold text-gray-800 mb-6 ml-[38%]">头像上传</h3>
        <x @click="toAvatarModal" class="ml-[30%] hover:scale-108 transition-all ease-out "></x>
      </div>

      <!-- 头像预览区：flex 居中，统一间距 -->
      <div class="flex justify-center mb-8 avatar-preview ">
        <div class="relative w-32 h-32 rounded-full overflow-hidden border-4 hover:scale-120 transition-all ease-out border-gray-200 shadow-sm preview-avatar">
          <img v-if="avatarUrl" :src="avatarUrl" alt="用户头像"
            class="w-full h-full object-cover transition-transform ">
          <div v-else class="w-full h-full bg-gray-200 flex items-center justify-center">
            <span class="text-gray-500 text-2xl">用户</span>
          </div>
        </div>
      </div>

      <!-- 上传控件区：flex 列布局，元素居中 -->
      <div class="flex flex-col items-center gap-4 avatar-uploader">
        <label
          class="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg shadow hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition">
          <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"
            xmlns="http://www.w3.org/2000/svg">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path>
          </svg>
          选择图片
          <input type="file" class="hidden" :accept="accept" @change="handleFileChange">
        </label>

        <!-- 进度条：占满可用宽度 -->
        <div v-if="uploadProgress > 0 && uploadProgress < 100"
          class="w-full bg-gray-200 rounded-full h-2.5 el-progress">
          <div class="bg-blue-600 h-2.5 rounded-full transition-all duration-300 ease-out"
            :style="{ width: uploadProgress + '%' }"></div>
        </div>

        <!-- 进度文本 -->
        <p v-if="uploadProgress > 0 && uploadProgress < 100" class="text-sm text-gray-500">
          上传中: {{ uploadProgress }}%
        </p>
      </div>

      <!-- 消息提示：固定间距，自适应背景色 -->
      <div v-if="message.show" class="mt-4 p-4 rounded-lg text-white"
        :class="message.type === 'success' ? 'bg-green-500' : 'bg-red-500'">
        <div class="flex items-center">
          <svg v-if="message.type === 'success'" class="w-5 h-5 mr-2" fill="none" stroke="currentColor"
            viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
          </svg>
          <svg v-else class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"
            xmlns="http://www.w3.org/2000/svg">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
          </svg>
          <span>{{ message.text }}</span>
        </div>
      </div>
    </div>
  </div>
</template>



<style scoped>
/* 组件过渡动画 */
.avatar-upload-container {
  transition: all 0.3s ease;
}

.avatar-upload-container:hover {
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
}
</style>